package org.csu.myPetStore.persistence.impl;

import org.csu.myPetStore.domain.CloseSource;
import org.csu.myPetStore.domain.Sequence;
import org.csu.myPetStore.persistence.DBUtil;
import org.csu.myPetStore.persistence.SequenceDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SequenceDAOImpl implements SequenceDAO {

    private static final String GET_SEQUENCE = "SELECT name, nextid FROM SEQUENCE WHERE NAME = ?";
    private static final String UPDATE_SEQUENCE = " UPDATE SEQUENCE SET NEXTID = ? WHERE NAME = ?";

    @Override
    public Sequence getSequence(Sequence sequence) {
        Sequence sequence1 = null;
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(GET_SEQUENCE);
            preparedStatement.setString(1,sequence.getName());
            ResultSet resultSet = preparedStatement.executeQuery();

            if(resultSet.next()){
                sequence = new Sequence();
                sequence.setName(resultSet.getString(1));
                sequence.setNextId(resultSet.getInt(2));
            }

            CloseSource closeSource = new CloseSource();
            closeSource.closeSource(connection,preparedStatement,resultSet,null);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sequence;
    }

    @Override
    public void updateSequence(Sequence sequence) {
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SEQUENCE);
            preparedStatement.setInt(1,sequence.getNextId());
            preparedStatement.setString(2,sequence.getName());

            int result = preparedStatement.executeUpdate();
            if(result == 1)
                System.out.println("updateSequence 成功");

            CloseSource closeSource = new CloseSource();
            closeSource.closeSource(connection,preparedStatement,null,null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
